package com.mf.utils;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @Author: lmf
 * @Create: 2024/7/8 10:25
 * Description:
 */
@Slf4j
public class CommonUtils {
    public static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    public static final int CHARACTERS_LENGTH = CHARACTERS.length();
    /**
     * MD5加密
     */
    public static String MD5(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] digest = md5.digest(str.getBytes(StandardCharsets.UTF_8));
            StringBuilder stringBuilder = new StringBuilder();
            for (byte item : digest) {
                stringBuilder.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
            }
            return stringBuilder.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            log.error("MD5加密失败:{}", e.getMessage());
        }
        return null;
    }

    /**
     * 获取随机数
     */
    public static String getRandomNumber(int length) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            stringBuilder.append((int) (Math.random() * 10));
        }
        return stringBuilder.toString();
    }

    /**
     * 生成指定长度字符串
     */
    public static String getRandomString(int length) {

        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(CHARACTERS_LENGTH);
            char randomChar = CHARACTERS.charAt(index);
            stringBuilder.append(randomChar);
        }
        return stringBuilder.toString();
    }

    /**
     * 获取UUID
     */
    public static String getUUID() {
        return java.util.UUID.randomUUID().toString().replace("-", "");
    }
}
